const { envList } = require("../../envList");
const { QuickStartPoints, QuickStartSteps } = require("./constants");
const app = getApp();
const cloudUrl = app.globalData.cloudUrl;

Page({
  data: {
    knowledgePoints: QuickStartPoints,
    steps: QuickStartSteps,
    //////////////////////
    cloudUrl:app.globalData.cloudUrl,
    airoot:app.globalData.airoot,
    waveArr:[{height:20},{height:60},{height:30}],
    aiurl:"https://u88368-9b5c-68b3652e.westb.seetacloud.com:8443/file=/tmp/gradio/474dfb954ed6c86cd95764a5194ddc0df40bd6d2/audio.wav",
    airunning:false,
    btnName:"播放声音",
    voiceSource:null,
    menus:[{img:"",url:cloudUrl+"btn_sy",select:true},{url:cloudUrl+"btn_sk",select:false},{url:cloudUrl+"btn_cgx",select:false},{url:cloudUrl+"btn_wd",select:false}],
    menuIndex:0,
    proArr:[
    {id:"pro1",id2:"num1",numLeft:0,num:25,angle:120,tempAngle:51,clipPath:"",top:0,numArr:[{char:"0",left:0},{char:"0",left:-30},{char:"p",left:-30}]},
    {id:"pro2",id2:"num2",numLeft:0,num:25,angle:120,tempAngle:53,top:80,numArr:[{char:"0",left:0},{char:"0",left:-30},{char:"p",left:-30}]},
    {id:"pro3",id2:"num3",numLeft:0,num:25,angle:120,tempAngle:55,top:0,numArr:[{char:"0",left:0},{char:"0",left:-30},{char:"p",left:-30}]}
    ],
    socketOpen:false,
    inputContent:"",
    sendContent:"",
    session_hash:"",
    generating:false,
    voicePath:"",
    voiceCompleted:false,
    isShowPlay:false,
    generProWidth:153,
    generProLeft:153,
    generProTimeId:0,
    playTimeId:0,
    playRotate:0,
    downAngle:0,
    moveAngle:0,
    proCtnWidth:0
    },

  copyCode(e) {
    const code = e.target?.dataset?.code || '';
    wx.setClipboardData({
      data: code,
      success: () => {
        wx.showToast({
          title: '已复制',
        })
      },
      fail: (err) => {
        console.error('复制失败-----', err);
      }
    })
  },
  onLoad(e){
    
    //音浪初始化
    var arr = this.data.waveArr;
    for(var i=0; i<18; i++){
      arr[i] = {height:0};
    }
    this.setData({waveArr:arr});
    //wx.cloud.init({env:'cloud1-8g5uy3ar0a5a684b'});//初始化云开发
    this.onMenuClick(e, 0);
    //圆形遮罩
    const proArr = this.data.proArr;
    this.drawProMask(0, 0);
    this.drawProMask(1, 0);
    this.drawProMask(2, 0);

    this.onSocketReconect();
    setInterval(this.onSocketReconect, 1000*60*60);
    ///return;
    var idx = 0;
    for(var i=0; i<3; i++){
      const query = wx.createSelectorQuery()
      const q = query.select('#pro' + (i+1))
      q.boundingClientRect()
      q.context()
      q.scrollOffset()
      query.exec(function(res){
        //console.log(res);
        const vx = res[0].left + res[0].width / 2;
        const vy = res[0].top + res[0].height / 2;
        proArr[idx].centerPos = {x:vx, y:vy};
        proArr[idx].res = res[0];
        idx ++;
      })
      //console.log("----------------");
    }
    /**var posA = { x: 10, y: -1 };
    var posB = { x: -5, y: -5 };
    var posC = { x: -5, y: 0 };
    var angle = this.getAngle(posA, posB, posC);
    //console.log("angle="+angle);
    //angle = this.getAngle(posA, posC, posB);
    //console.log("angle="+angle);
    angle = this.getAngle(posB, posA, posC);**/

    this.exeSelector(this.getProWidth, "#proCtn");
  },
  getProWidth(res){
    this.setData({proCtnWidth:res[0].width});
  },
  exeSelector(fun, id){
    const query = wx.createSelectorQuery();
    const q = query.select(id);
    q.boundingClientRect();
    //q.context()
    //q.scrollOffset()
    query.exec(fun);
  },
  onSocketReconect(){
    const session_hash = Math.random().toString(36).substring(2);
    this.setData({session_hash:session_hash});
    
  },
  onInputBlur(e){
    this.setData({inputContent:e.detail.value});
  },
  /**点击提交语音按钮 */
  onSubmitClick(e){
    setTimeout(this.submitTxt, 60);
  },
  submitTxt(){
    const str = this.data.inputContent;
    if(str){
      const generating = this.data.generating;
      if(generating){//语音正在生成中...
        return;
      }
      if(this.data.sendContent == str){//不要提交相同的语音
        return;
      }
      if(str == "在此处输入配音文本..."){
        return;
      }
      var timeid = setInterval(this.generTimer, 200);
      this.setData({generating:true,sendContent:str,voiceCompleted:false,generProLeft:this.data.generProWidth,generProTimeId:timeid});

      console.log("-->提交语音="+str);
      //const data = {fn_index:1,session_hash:this.data.session_hash};
      //this.sendSocketMsg(data);

      const socketOpen = this.data.socketOpen;
      if(socketOpen){
        wx.closeSocket();
      }
      this.onSocketInit();
    }
    else{
      console.warn("请输入文本内容!");
    }
  },
  generTimer(){
    var proleft = this.data.generProLeft;
    proleft -= 11.77;
    if(proleft < 0){
      proleft = this.data.generProWidth;
    }
    this.setData({generProLeft:proleft});
  },
  onSocketInit(){
    wx.connectSocket({
      url: 'wss://u88368-9b5c-68b3652e.westb.seetacloud.com:8443/queue/join',
      header:{
        'content-type': 'application/json'
      }
    })
    const _this = this;
    wx.onSocketOpen(function(res) {
      console.log("-->onSocketOpen");
      console.log(res);
      _this.setData({socketOpen:true});
    })
    wx.onSocketError(function(res) {
      console.log("-->onSocketError");
      console.log(res);
    })
    wx.onSocketClose(function(res) {
      console.log("-->onSocketClose");
      console.log(res);
      _this.setData({socketOpen:false});
    })
    wx.onSocketMessage(function(res) {
      console.log("-->onSocketMessage");
      console.log(res);

      var resdata = JSON.parse(res.data);
      if(resdata.msg == "send_hash"){
        const data = {fn_index:1,session_hash:_this.data.session_hash};
        _this.sendSocketMsg(data);
      }
      else if(resdata.msg == "send_data"){
        const content = _this.data.inputContent;
        const data = {data:[false,"Amachi_Haru_rur","悲伤",content,"zh"],event_data:null,fn_index:1,session_hash:_this.data.session_hash};
        _this.sendSocketMsg(data);
      }
      else if(resdata.msg == "process_completed"){
        _this.setData({generating:false});
        if(resdata.success == true){
          const path = resdata.output.data[0].name;
          const url = _this.data.airoot + path;
          _this.setData({voicePath:path, aiurl:url,voiceCompleted:true,isShowPlay:true});
          clearInterval(_this.data.generProTimeId);
          //_this.onPlayClick();
        }
      }
      
      //{"fn_index":1,"session_hash":"tontc947r5"}
    })
  },
  sendSocketMsg(data){
    var json = JSON.stringify(data);
    console.log("-->发送消息:" + json);
    wx.sendSocketMessage({
      data:json
    })
  },
  onMenuClick(e, index=-1){
    var idx = 0;
    if(index == -1){
      idx = e.currentTarget.dataset.index;
    }
    else{
      idx = index;
    }
    const arr = this.data.menus;
    for(var i=0; i<arr.length; i++){
      if(idx == i){
        arr[i].select = true;
        arr[i].img = arr[i].url + ".png";
      }
      else{
        arr[i].select = false;
        arr[i].img = arr[i].url + "1.png";
      }
    }
    this.setData({menus:arr,menuIndex:idx});
  },
  onWavePlay(e){
    var audioCtx = wx.createWebAudioContext();
    this.setData({audioCtx:audioCtx});
    const loadAudio = (url) => {
      console.log(url);
      return new Promise((resolve) => {
        wx.request({
          url,
          responseType: 'arraybuffer',
          success: res => {
            audioCtx.decodeAudioData(res.data, buffer => {
              resolve(buffer)
            }, err => {
              console.error('decodeAudioData fail', err)
              reject()
            })
          },
          fail: res => {
            console.error('request fail', res)
            reject()
          }
        })
      })
    }
    const play = () => {
      var _this = this;
      loadAudio(this.data.aiurl).then(buffer => {
        let source = audioCtx.createBufferSource();
        source.buffer = buffer;
        this.setData({audioCtx:audioCtx,voiceSource:source});
        
        //source.connect(audioCtx.destination);
        const analyser = audioCtx.createAnalyser();
        this.setData({analyser:analyser});
        source.connect(analyser);
        //analyser.fftSize = 512;
        //const bufferLength = analyser.fftSize;
        analyser.connect(audioCtx.destination);
        source.onended = this.onVoicePlayEnd;

        source.start();
        setInterval(_this.onFrame, 1000/60);
      }).catch(() => {
        console.log('fail')
      })
    }
    
    play();
  },
  onVoicePlayEnd(e){
    console.log("-----------");
    console.log(e);
    this.setData({airunning:false,btnName:"播放声音",isShowPlay:true});
    clearInterval(this.data.playTimeId);
  },
  onFrame(){
    const dataArray = new Uint8Array(18);
    var analyser = this.data.analyser;
    analyser.getByteTimeDomainData(dataArray);
    //console.log("-----------------------");
    //console.log(dataArray);
    
    var arr = this.data.waveArr;
    arr.length = 0;
    //console.log(dataArray);
    const maxH = 104;
    for(var i=0; i<dataArray.length; i++){
      var v = dataArray[i] / 128.0;
      // 计算波形点的纵坐标
      var y = 94 + (maxH - v * maxH) * 10;
      arr.push({height:y});
    }
    //console.log(arr);
    this.setData({waveArr:arr});
    return;
    var frame = this.data.testFrame;
    console.log("dsdssddsds" + (frame));
    frame ++;
    this.setData({testFrame:frame});
  },
  onPlayClick(e){
    var running = this.data.airunning;
    if(!running){
      this.onWavePlay();
      const timeid = setInterval(this.onPlayFrame, 1000/60);
      this.setData({airunning:true,btnName:"停止声音",isShowPlay:false,playTimeId:timeid});
    }
    else{
      this.data.voiceSource.stop();
      this.setData({airunning:false,btnName:"播放声音",isShowPlay:true});
      clearInterval(this.data.playTimeId);
    }
    /**wx.navigateTo({
      url: '/pages/waveTest/waveTest',
    })**/
  },
  onPlayFrame(){
    var rotate = this.data.playRotate;
    rotate += 2;
    this.setData({playRotate:rotate});
  },
  onProStart(e){
    console.log("------onProStart------");
    console.log(e);
    //this.onProMove(e);

    const idx = e.currentTarget.dataset.index;
    const angle = this.getAngleByIndex(idx, e);
    this.setData({downAngle:angle});
  },
  getAngleByIndex(idx, e){
    const proArr = this.data.proArr;
    const centerPos = proArr[idx].centerPos;
    var vx = e.touches[0].clientX - centerPos.x;
    var vy = e.touches[0].clientY - centerPos.y;
    const angle = this.getAngle({x:vx, y:vy});
    return angle;
  },
  onProMove(e){
    //console.log("------onProMove------");
    //console.log(e);
    const idx = e.currentTarget.dataset.index;
    const proArr = this.data.proArr;
    const res = proArr[idx].res;
    const endPos = proArr[idx].endPos;
    const centerPos = proArr[idx].centerPos;
    
    const dAngle = this.data.downAngle;
    const angle = this.getAngleByIndex(idx, e);
    var value = angle - dAngle;
    /**if(e.touches[0].clientX > centerPos.x){//向右，顺时针
      if(value < 0){
        value = 360 + value;
      }
    }
    else{//向左，逆时针
      if(angle + dAngle < 0){
        value = -dAngle;
      }
    }**/
    //console.log("dAngle="+dAngle+",angle="+angle+",value="+value);
    this.drawProMask(idx, value);
    

    /**var vx = res.left + endPos[0] / 100 * res.width;
    var vy = res.top + endPos[1] / 100 * res.height;
    var posA = {x:vx, y:vy};

    vx = e.touches[0].clientX;
    vy = e.touches[0].clientY;
    var posB = {x:vx, y:vy};

    vx = centerPos.x;
    vy = centerPos.y;
    var posC = {x:vx, y:vy};
    console.log("-------");
    console.log(posA);
    console.log(posB);
    console.log(posC);
    var angle = this.getAngle(posA, posB, posC);
    console.log("angle="+angle);
    angle = this.getAngle(posA, posC, posB);
    console.log("angle="+angle);
    angle = this.getAngle(posB, posC, posA);
    console.log("angle="+angle);
    angle = this.getAngle(posB, posA, posC);
    console.log("angle="+angle);**/
  },
  onProEnd(e){
    //console.log("------onProEnd------");
    //console.log(e);
    const proArr = this.data.proArr;
    var num = 0;
    for(var i=0; i<proArr.length; i++){
      proArr[i].angle = proArr[i].tempAngle;
      num = (proArr[i].tempAngle / 360);
      proArr[i].num = num;
    }
    this.setData({proArr:proArr});
  },
  getAngle(A, B, C) {

    var rot = Math.atan2(A.y, A.x);
    rot = rot * 180 / Math.PI - 90;
    //console.log("+++++++"+rot);
    while ( rot < 0 )
    {
        rot += 360;
    }
    return rot;

    /**var diff_x = B.x - A.x,
    diff_y = B.y - A.y;
    //返回角度,不是弧度
    return 360*Math.atan(diff_y/diff_x)/(2*Math.PI);**/

    var AB = Math.sqrt(Math.pow(A.x - B.x, 2) + Math.pow(A.y - B.y, 2));
    var AC = Math.sqrt(Math.pow(A.x - C.x, 2) + Math.pow(A.y - C.y, 2));
    var BC = Math.sqrt(Math.pow(B.x - C.x, 2) + Math.pow(B.y - C.y, 2));
    var cosA = (
                Math.pow(AB, 2) + Math.pow(AC, 2) - Math.pow(BC, 2)
              ) / (
                2 * AB * AC
              );
    var angleA = Math.round( Math.acos(cosA) * 180 / Math.PI );
    return angleA;

    //以下是错的
    // 计算向量AB和向量BC
    var vectorAB = { x: B.x - A.x, y: B.y - A.y };
    var vectorBC = { x: C.x - B.x, y: C.y - B.y };
   
    // 计算点积
    var dotProduct = vectorAB.x * vectorBC.x + vectorAB.y * vectorBC.y;
   
    // 计算向量的模（长度）
    var modulusAB = Math.sqrt(vectorAB.x * vectorAB.x + vectorAB.y * vectorAB.y);
    var modulusBC = Math.sqrt(vectorBC.x * vectorBC.x + vectorBC.y * vectorBC.y);
   
    // 计算夹角cos值
    var cosAngle = dotProduct / (modulusAB * modulusBC);
   
    // 通过cos值计算角度
    var angle = Math.acos(cosAngle) * 180 / Math.PI;
   
    return angle;
  },
  drawProMask(idx = 0, angle = 0){
    const proObj = this.data.proArr[idx];
    var curAngle = proObj.angle + angle;
    if(curAngle > 360){
      curAngle = 360;
    }
    if(curAngle < 0){
      curAngle = 0;
    }
    var arr = [[50,50]];
    var steps = Math.floor(curAngle / 360 * 100);
    if(steps < 10){
      steps = 10;
    }
    //console.log("steps="+steps);
    var rt = 90;
    var step = curAngle / steps;
    for(var i=0; i<=steps; i++){
      var vx = 50 + 50 * Math.cos(rt * Math.PI / 180);
      var vy = 50 + 50 * Math.sin(rt * Math.PI / 180);
      arr.push([vx, vy]);
      rt += step;
    }
    //console.log(rt);
    
    //"polygon(50% 50%,50% 100%,25% 100%)"
    var str = "polygon(";
    for(var i=0; i<arr.length; i++){
      str += arr[i][0] + "% ";
      if(i == arr.length - 1){
        str += arr[i][1] + "%";
      }
      else{
        str += arr[i][1] + "%,";
      }
    }
    str += ")";
    var pos = arr[arr.length - 1];
    //console.log("curAngle=" + curAngle);
    proObj.clipPath = str;
    proObj.tempAngle = curAngle;
    proObj.endPos = pos;

    //设置图片数字
    var numArr = proObj.numArr;
    numArr.length = 0;
    var num = Math.floor(curAngle / 360 * 100);
    //console.log("num="+num);
    var str = num + "";
    var char = "";
    var left = 0;
    for(var j=0; j<str.length; j++){
      char = str.charAt(j);
      if(j == 0){
        left = 0;
      }
      else{
        left = -30;
      }
      numArr.push({char:char,left:left});
    }
    numArr.push({char:"p",left:-30});
    this.setData({proArr:this.data.proArr});

    //图片数字居中对齐
    this.proAutoSize(idx);
  },
  proAutoSize(idx = 0){
    //console.log("proAutoSize,idx="+idx);
    const proObj = this.data.proArr[idx];
    const proWidth = this.data.proCtnWidth;
    const _this = this;
    this.exeSelector(function(res){
      var vx = proWidth - res[0].width >> 1;
      proObj.numLeft = vx;
      _this.setData({proArr:_this.data.proArr});
    }, "#"+proObj.id2);
  },
  onProNumLoaded(e){
    //console.log(e);
    const idx = e.currentTarget.dataset.index;
    //console.log("loaded=" + idx);
    this.proAutoSize(idx);
  },
  discoverCloud() {
    wx.switchTab({
      url: '/pages/examples/index',
    })
  },

  gotoGoodsListPage() {
    wx.navigateTo({
      url: '/pages/goods-list/index',
    })
  },
});
